/**
 * 
 */
package uniandes.dermatologia.tasks;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import uniandes.dermatologia.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

/**
 * @author Julio
 *
 */
public class ImageDownloadTask extends AsyncTask<String, Void, Object> {
	
	private static final String IMAGE_URL = "http://157.253.236.91:3000/images_services";

	private static final String ID = "id";
	
	private Context context;
	
	private ImageView i;
	
	public ImageDownloadTask(Context context)
	{
		this.context = context;
	}

	@Override
	protected Object doInBackground(String... params) {
		Bitmap bitmap = null;
		try 
		{
			HttpPost post = new HttpPost(IMAGE_URL);
			String userName = params[0];
	        ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(1);
	        BasicNameValuePair nameValuePair = new BasicNameValuePair(ID, userName);
	        nameValuePairs.add(nameValuePair);
	        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
	        post.setEntity(entity);
	        HttpClient httpclient = new DefaultHttpClient();
            Log.d("request", post.getURI().toString());
            HttpResponse response = httpclient.execute(post);
            HttpEntity httpEntity = response.getEntity();
            InputStream is = httpEntity.getContent();
	        BufferedInputStream bis = new BufferedInputStream(is);
	        bitmap = BitmapFactory.decodeStream(bis);
	        bis.close();
	        is.close();
			
			i = (ImageView)((Activity) context).findViewById(R.id.imgQuestion);
			 
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	
	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		if(result == null)
		{
			i.setVisibility(View.GONE);
		}
		else
		{
			i.setImageBitmap((Bitmap)result);
		}
	}

}
